package com.feishi.core.media.opencv;

import com.feishi.core.media.opencv.util.OpenCvUtil;
import com.feishi.core.util.common.FileUtil;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-4-20 14:56
 **/
public class HelloOpenCV {
    private static void testMat() {

        System.out.println("Welcome to OpenCV " + Core.VERSION);
        Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
        System.out.println("OpenCV Mat: " + m);
        Mat mr1 = m.row(1);
        mr1.setTo(new Scalar(1));
        Mat mc5 = m.col(5);
        mc5.setTo(new Scalar(5));
        System.out.println("OpenCV Mat data:\n" + m.dump());
    }

    public static void main(String[] args) {
        OpenCvUtil.loadLibrary();
        String path="/home/caixq/Music/CloudMusic/MV/test.mp4";
        String out=FileUtil.getTempDir();
//        readVideoToImg(path, out);
        getDiff(path, out+"/out");
    }

    private static void getDiff(String videoPath, String outDir) {
        VideoCapture videoCapture=new VideoCapture(videoPath);
        Mat mat=new Mat();
        Mat preMat=mat;
        Mat diff=new Mat();
        int i=0;
        FileUtil.createDir(outDir);
        while (videoCapture.read(mat)){
            Imgcodecs.imwrite(outDir+"/out"+i+".png",mat);
            Core.absdiff(mat,preMat,diff);

            Imgcodecs.imwrite(outDir+"/out"+i+"_diff.png",diff);
            i++;

            preMat=mat;
            mat=new Mat();
        }

    }

    private static void readVideoToImg(String videoPath,String outDir) {

        VideoCapture videoCapture=new VideoCapture(videoPath);
        Mat mat=new Mat();

        int i=0;
        System.out.println("start write img");
        while (videoCapture.read(mat)){
            Imgcodecs.imwrite(outDir+"/out"+i+".png",mat);
            mat=new Mat();
        }
        System.out.println("write img all");
    }
}
